package com.kgc.web;

import com.kgc.dao.AdminDao;
import com.kgc.entity.Admin;
import com.kgc.utils.CodecUtils;
import com.kgc.vo.R;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "AdminServlet", value = "/AdminServlet")
public class AdminServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求标识
        String opt = request.getParameter("opt");
        PrintWriter writer = response.getWriter();
        HttpSession session = request.getSession();
        AdminDao adminDao = new AdminDao();

        if ("captcha".equals(opt)) {
            // 验证码验证码
            // 1.获取用户输入验证码
            String captcha = request.getParameter("captcha");
            // 2.获取Session验证码
            String code = (String) session.getAttribute("code");
            if (captcha.equalsIgnoreCase(code)) {
                writer.write("ok");
            } else {
                writer.write("error");
            }
        } else if ("login".equals(opt)) { // 登录功能
            String captcha = request.getParameter("captcha");
            // 1.获取Session验证码
            String code = (String) session.getAttribute("code");
            if (captcha.equalsIgnoreCase(code)) {
                // 2.获取用户名和密码
                String email = request.getParameter("email");
                String password = request.getParameter("password");
                Admin admin = adminDao.selectLogin(email);
                if (admin != null) {
                    String salt=admin.getSalt();
                    if(CodecUtils.match(admin.getPassword(),password,salt)){
                        session.setAttribute("admin", admin);
                        writer.write(R.success("登录成功！").toJSON());
                    }else {
                        writer.write(R.error("登录失败！密码有误！").toJSON());
                    }
                } else {
                    writer.write(R.error("登录失败！邮箱不存在！").toJSON());
                }
            } else {
                writer.write("2");
            }
        }
        }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
